<?php
	require_once("model//dish.php");
	require_once("model//review.php");
	require_once("model//restaurant.php");
?>
<?php
	
	function mysql_prep($value){
		$magic_quotes_active = get_magic_quotes_gpc();
		$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
		if( $new_enough_php ) { // PHP v4.3.0 or higher
			// undo any magic quote effects so mysql_real_escape_string can do the work
			if( $magic_quotes_active ) { 
				$value = stripslashes( $value ); 
			}
			$value = mysql_real_escape_string( $value );
		} else { // before PHP v4.3.0
			// if magic quotes aren't already on then add slashes manually
			if( !$magic_quotes_active ) { 
				$value = addslashes( $value ); 
			}
			// if magic quotes are active, then the slashes already exist
		}
		return $value;
	}
	
	function checkIfUserNameExists($userName){
		$query = "SELECT UserID FROM ".USER_TABLE." WHERE Username = '{$userName}' ";
		$data = mysql_query($query);
		if(mysql_num_rows($data) == 0){
			return false;			
		}else{
			return true;
		}
	}
	
	function getUserId($userName){
		$query = "SELECT UserID FROM ".USER_TABLE." WHERE Username = '{$userName}' ";
		$data = mysql_query($query);
		if(mysql_num_rows($data) == 0){
			return -1;
		}else{
			$row = mysql_fetch_assoc($data);
			return $row['UserID'];
		}
	}
	
	function insertUser($userName,$password){
		$exists = checkIfUserNameExists($userName);
		$result = "";
		if($exists){
			$result = "Username already exists";
		}else{
			//Doesn't Exist
			$query = "INSERT INTO ".USER_TABLE." (UserID,Username,PasswordHash) VALUES (UUID(),'{$userName}',SHA('{$password}'))";
			$data = mysql_query($query);
			if(!$data){
				$result = "Registration Failed";
			}else{
				$result = "Registration Success";
			}
		}
		return $result;
	}
	
	function authenticateUser($userName,$password){
		$exists = checkIfUserNameExists($userName);
		$result = "";
		if(!$exists){
			$result = "Username not found";
		}else{
			$query = "SELECT UserID FROM ".USER_TABLE." WHERE PasswordHash = SHA('{$password}')";
			$data = mysql_query($query);
			if(mysql_num_rows($data) == 1){
				$result = "Authentication Success";
			}else{
				$result = "Authentication Failed";
			}
		}
		return $result;
	}
	
	function checkIfAlreadyFollowing($meId,$friendId){
		$query = "SELECT * FROM ".FOLLOWS_TABLE." WHERE Follower = '{$meId}' AND Follows = '{$friendId}'";
		$data = mysql_query($query);
		if(mysql_num_rows($data) == 0){
			return false;
		}else{
			return true;
		}
	}
	
	function addFriend($me,$friend){
		$meId = getUserId($me);
		if($meId == -1){
			return "You are not a registered user";
		}
		$friendId = getUserId($friend);
		if($friendId == -1){
			return $friend." is not a registered user";
		}
		$exists = checkIfAlreadyFollowing($meId,$friendId);
		if($exists){
			return "You are already following ".$friend;
		}
		$result = "";
		$query = "INSERT INTO ".FOLLOWS_TABLE." (Follower,Follows) VALUES ('{$meId}','{$friendId}')";
		$data = mysql_query($query);
		if(!$data){
			$result = "Adding Friend Failed";
		}else{
			$result = "You are now following ".$friend;
		}
		return $result;
	}
	
	function removeFriend($me,$friend){
		$meId = getUserId($me);
		if($meId == -1){
			return "You are not a registered user";
		}
		$friendId = getUserId($friend);
		if($friendId == -1){
			return $friend." is not a registered user";
		}
		$result = "";
		$query = "DELETE FROM ".FOLLOWS_TABLE." WHERE Follower = '{$meId}' AND Follows = '{$friendId}'";
		$data = mysql_query($query);
		if(!$data){
			$result = "Removing Friend Failed";
		}else{
			$result = "You are not following ".$friend;
		}
		return $result;
	}
	
	function getFriends($me)
	{
		$meId = getUserId($me);
		if($meId == -1){
			return "You are not a registered user";
		}
		$result = "";
		$query = "SELECT Username FROM ".USER_TABLE." WHERE UserID IN (SELECT Follows FROM ".FOLLOWS_TABLE." WHERE Follower = '{$meId}')";
		$data = mysql_query($query);
		if(!$data){
			return "Error Getting Friends List";
		}else{
			$userArray = array();
			while($row = mysql_fetch_assoc($data)){
				array_push($userArray,$row['Username']);
			}
			$userJSONArray = array();
			foreach($userArray as $value){
				array_push($userJSONArray,array("username" => $value));
			}
			$result = json_encode($userJSONArray);
		}
		return $result;
	}
	
	function addDish($dish,$imageName){
		try{
			$dishData = json_decode($dish,true);
		}catch(Exception $e){
			return "Error";
		}
		$data = $dishData['dish'];
		
		$me = $data['username'];
		$meId = getUserId($me);
		if($meId == -1){
			return "Error: You are not a registered user, ".$me;
		}
		
		$review = $data['review'];
		$restaurant = $review['restaurant'];
		
		$query = "INSERT INTO ".RESTAURANT_TABLE." (Name,Street,City,State,ZipCode) VALUES ('".addslashes($restaurant['name'])."','".addslashes($restaurant['street'])."','".addslashes($restaurant['city'])."','".addslashes($restaurant['state'])."','".addslashes($restaurant['zipcode'])."')";
		
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Restaurant Failed";
		}
		$restId = mysql_insert_id();
		
		$query = "INSERT INTO ".REVIEW_TABLE." (RestaurantID,Comments,Rating) VALUES ({$restId},'{$review['comments']}',{$review['rating']})";
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Review Failed, ".$query;
		}
		$reviewId = mysql_insert_id();
		
		$query = "INSERT INTO ".DISH_TABLE." (ReviewID,Disher,Image) VALUES ({$reviewId},'{$meId}','{$imageName}')";
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Dish Failed";
		}
		return "Dish added successfully";
	}
	
	function storeDish($dish,$imageName){
		try{
			$dishData = json_decode($dish,true);
		}catch(Exception $e){
			return "Error";
		}
		$data = $dishData['dish'];
		
		$me = $data['username'];
		$meId = getUserId($me);
		if($meId == -1){
			return "Error: You are not a registered user, ".$me;
		}
		
		$review = $data['review'];
		$restaurant = $review['restaurant'];
		
		$query = "INSERT INTO ".RESTAURANT_TABLE." (Name,Street,City,State,ZipCode) VALUES ('{$restaurant['name']}','{$restaurant['street']}','{$restaurant['city']}','{$restaurant['state']}','{$restaurant['zipcode']}')";
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Restaurant Failed";
		}
		$restId = mysql_insert_id();
		
		$query = "INSERT INTO ".REVIEW_TABLE." (RestaurantID,Comments,Rating) VALUES ({$restId},'{$review['comments']}',{$review['rating']})";
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Review Failed, ".$query;
		}
		$reviewId = mysql_insert_id();
		
		$dishAdminId = getUserId('DishIt');
		if($dishAdminId == -1){
			return "Error: You are not a registered user, ".$me;
		}
		$query = "INSERT INTO ".DISH_TABLE." (ReviewID,Disher,ForWhom,Image) VALUES ({$reviewId},'{$dishAdminId}','{$meId}','{$imageName}')";
		$data = mysql_query($query);
		if(!$data){
			return "Error: Adding Dish Failed";
		}
		return "Dish added successfully";
	}
	
	function getMySentDishes($me)
	{	
		$meId = getUserId($me);
		$query = "SELECT * FROM ".DISH_TABLE." WHERE Disher = '{$meId}' ORDER BY DishDate DESC";
		$dishdata = mysql_query($query);
		if(!$dishdata){
			return "Error in selecting dish";
		}
		$dishArray = array();
		while($dishes = mysql_fetch_assoc($dishdata)){
			$reviewId = $dishes['ReviewID'];
			$query = "SELECT * FROM ".REVIEW_TABLE." WHERE ID = {$reviewId}";
			$reviewdata = mysql_query($query);
			if(!$reviewdata){
				return "Error in selecting review";
			}
			$reviews = mysql_fetch_assoc($reviewdata);
			$restaurantId = $reviews['RestaurantID'];
			$query = "SELECT * FROM ".RESTAURANT_TABLE." WHERE ID = {$restaurantId}";
			$restaurantdata = mysql_query($query);
			if(!$restaurantdata){
				return "Error in selecting review";
			}
				
			$resData = mysql_fetch_assoc($restaurantdata);
			$restaurant = new Restaurant();
			$restaurant->name = $resData['Name'];
			$restaurant->street = $resData['Street'];
			$restaurant->city = $resData['City'];
			$restaurant->state = $resData['State'];
			$restaurant->zipcode = $resData['ZipCode'];
				
			$review = new Review();
			$review->restaurant = $restaurant;
			$review->comments = $reviews['Comments'];
			$review->rating = $reviews['Rating'];
				
			$newDish = new Dish();
			$newDish->disher = $me;
			$newDish->review = $review;
			$newDish->image = $dishes['Image'];	
			
			array_push($dishArray,$newDish);
		}
		$dishJsonArray = array();
		foreach($dishArray as $value){
			array_push($dishJsonArray,array("dish" => array("username" => $me, "imageURL" => BASE_URL."\\".TILDE.DB_USER."\\".SERVER_DIR."\\".IMAGES_DIR."\\".$value->image,"review" => array("comments" => $value->review->comments,"rating" => $value->review->rating, "restaurant" => array("name" => $value->review->restaurant->name, "street" => $value->review->restaurant->street, "city" => $value->review->restaurant->city, "state" => $value->review->restaurant->state, "zipcode" => $value->review->restaurant->zipcode)))));
		}
		return json_encode($dishJsonArray);
	}
	
	function getMyReceivedDishes($me)
	{
		$meId = getUserId($me);
		$query = "SELECT * FROM ".DISH_TABLE." WHERE Disher IN (SELECT Follows FROM ".FOLLOWS_TABLE." WHERE Follower = '{$meId}') OR ForWhom = '{$meId}' ORDER BY DishDate DESC";
		$dishdata = mysql_query($query);
		if(!$dishdata){
			return "Error in selecting dish for following ".$me;
		}
		$dishArray = array();
		while($dishes = mysql_fetch_assoc($dishdata)){
			$reviewId = $dishes['ReviewID'];
			$query = "SELECT * FROM ".REVIEW_TABLE." WHERE ID = {$reviewId}";
			$reviewdata = mysql_query($query);
			if(!$reviewdata){
				return "Error in selecting review";
			}
			
			$reviews = mysql_fetch_assoc($reviewdata);
			$restaurantId = $reviews['RestaurantID'];
			$query = "SELECT * FROM ".RESTAURANT_TABLE." WHERE ID = {$restaurantId}";
			$restaurantdata = mysql_query($query);
			if(!$restaurantdata){
				return "Error in selecting restaurant";
			}
				
			$resData = mysql_fetch_assoc($restaurantdata);
			$restaurant = new Restaurant();
			$restaurant->name = $resData['Name'];
			$restaurant->street = $resData['Street'];
			$restaurant->city = $resData['City'];
			$restaurant->state = $resData['State'];
			$restaurant->zipcode = $resData['ZipCode'];
				
			$review = new Review();
			$review->restaurant = $restaurant;
			$review->comments = $reviews['Comments'];
			$review->rating = $reviews['Rating'];
				
			$query = "SELECT Username FROM ".USER_TABLE." WHERE UserID = '{$dishes['Disher']}'";
			$userdata = mysql_query($query);
			if(!$userdata){
				return "Error in selecting username";
			}
			$user = mysql_fetch_assoc($userdata);
			
			$newDish = new Dish();
			$newDish->disher = $user['Username'];
			$newDish->review = $review;
				
			array_push($dishArray,$newDish);
		}
		$dishJsonArray = array();
		foreach($dishArray as $value){
			array_push($dishJsonArray,array("dish" => array("username" => $value->disher, "imageURL" => BASE_URL."\\".TILDE.DB_USER."\\".SERVER_DIR."\\".IMAGES_DIR."\\".$value->image, "review" => array("comments" => $value->review->comments,"rating" => $value->review->rating, "restaurant" => array("name" => $value->review->restaurant->name, "street" => $value->review->restaurant->street, "city" => $value->review->restaurant->city, "state" => $value->review->restaurant->state, "zipcode" => $value->review->restaurant->zipcode)))));
		}
		return json_encode($dishJsonArray);
	}
	
	function getAllMyDishes($me)
	{	
		$meId = getUserId($me);
		$query = "SELECT * FROM ".DISH_TABLE." WHERE Disher = '{$meId}' OR ForWhom = '{$meId}' ORDER BY DishDate DESC";
		$dishdata = mysql_query($query);
		if(!$dishdata){
			return "Error in selecting dish";
		}
		$dishArray = array();
		while($dishes = mysql_fetch_assoc($dishdata)){
			$reviewId = $dishes['ReviewID'];
			$query = "SELECT * FROM ".REVIEW_TABLE." WHERE ID = {$reviewId}";
			$reviewdata = mysql_query($query);
			if(!$reviewdata){
				return "Error in selecting review";
			}
			$reviews = mysql_fetch_assoc($reviewdata);
			$restaurantId = $reviews['RestaurantID'];
			$query = "SELECT * FROM ".RESTAURANT_TABLE." WHERE ID = {$restaurantId}";
			$restaurantdata = mysql_query($query);
			if(!$restaurantdata){
				return "Error in selecting review";
			}
				
			$resData = mysql_fetch_assoc($restaurantdata);
			$restaurant = new Restaurant();
			$restaurant->name = $resData['Name'];
			$restaurant->street = $resData['Street'];
			$restaurant->city = $resData['City'];
			$restaurant->state = $resData['State'];
			$restaurant->zipcode = $resData['ZipCode'];
				
			$review = new Review();
			$review->restaurant = $restaurant;
			$review->comments = $reviews['Comments'];
			$review->rating = $reviews['Rating'];
				
			$newDish = new Dish();
			if($dishes['Disher'] === $meId){
				$newDish->disher = $me;
			}else{
				$newDish->disher = 'DishIt';
			}
			$newDish->review = $review;
			$newDish->image = $dishes['Image'];	
			
			array_push($dishArray,$newDish);
		}
		$dishJsonArray = array();
		foreach($dishArray as $value){
			array_push($dishJsonArray,array("dish" => array("username" => $value->disher, "imageURL" => BASE_URL."\\".TILDE.DB_USER."\\".SERVER_DIR."\\".IMAGES_DIR."\\".$value->image,"review" => array("comments" => $value->review->comments,"rating" => $value->review->rating, "restaurant" => array("name" => $value->review->restaurant->name, "street" => $value->review->restaurant->street, "city" => $value->review->restaurant->city, "state" => $value->review->restaurant->state, "zipcode" => $value->review->restaurant->zipcode)))));
		}
		return json_encode($dishJsonArray);
	}
	
?>